define(['jquery', 'bootstrap', 'backend', 'table', 'form','qrcode'], function ($, undefined, Backend, Table, Form,QRCode) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'classes/student/index?relType='+Config.relType+'&relId='+Config.relId+'&cid='+Config.cid,
                    add_url: 'classes/student/add?relType='+Config.relType+'&relId='+Config.relId+'&cid='+Config.cid,
                    edit_url: 'classes/student/edit?relType='+Config.relType+'&relId='+Config.relId+'&cid='+Config.cid,
                    multi_url: 'classes/student/multi?relType='+Config.relType+'&relId='+Config.relId+'&cid='+Config.cid,
                    del_url: 'classes/student/del?relType='+Config.relType+'&relId='+Config.relId+'&cid='+Config.cid,
                    table: 'class_student',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                queryParams: function (params) {
                    params.rel_type = Config.relType;
                    params.rel_id = Config.relId;
                    return params;
                },
                escape: false,
                pk: 'id',
                sortName: 'id', //要使排序生效，在前面添加 weigh desc, 并且数据表weigh字段不能全为0,controller里$list=...->order前再添加->order("weigh desc")
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'classes_id', title: '班级'},
                        {field: 'student_name', title: '学生'},
                        {field: 'add_time', title: '加入时间', formatter: Table.api.formatter.datetime},
                        {field: 'apply_statue', title: '报名状态'},
                        {field: 'apply_id', title: '支付定单号'},
                        {field: 'school_id', title: '学校'},
                        {field: 'pay', title: '支付', formatter: Controller.api.formatter.payButton, events: Controller.api.events.pay},
                        {field: 'status', title: '审核状态', formatter: Controller.api.formatter.status, operate: false},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate,
                            buttons: [
                                // {
                                //     name: 'detail',
                                //     classname: 'btn btn-xs btn-primary btn-click',
                                //     icon: 'fa fa-sitemap',
                                //     click: function (value, row, index) {
                                //         Backend.api.open('/adminht.php/dept/dept?relType=school&relId='+row.id+'&ref=addtabs', '组织结构2', {
                                //             max: true,
                                //             area: ['80%', '80%'],
                                //             //offset: ['0px', '0px'],
                                //             callback: function (data) {
                                //                 Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                                //             }
                                //         });
                                //     }
                                // }
                            ]
                        }
                    ]
                ]
            });


            // 为审核开关绑定事件
            $(document).on('click', '.btn-status', function () {
                var id = $(this).data('id');
                var status = $(this).data('status');
                var newStatus = status == 1 ? 0 : 1;
                var that = this;
                Layer.confirm('确认' + (newStatus == 1 ? '通过' : '取消通过') + '审核？', {icon: 3, title:'提示'}, function(index){
                    Fast.api.ajax({
                        url: 'classes/student/changestatus',
                        data: {id: id, status: newStatus}
                    }, function (data, ret) {
                        $(that).data('status', newStatus);
                        $(that).find('i').toggleClass('fa-toggle-on fa-toggle-off');
                        $(that).find('i').toggleClass('text-success text-danger');
                        Layer.close(index);
                        table.bootstrapTable('refresh');
                        return false;
                    });
                });
            });

            $(document).on('fa.event.success', function(event, data) {
                setTimeout(function() {
                    location.reload();
                }, 1000);
            });
            var script = document.createElement('script');
            script.src = '/assets/js/backend/common/index.js';
            document.head.appendChild(script);
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            var script = document.createElement('script');
            script.src = '/assets/js/backend/common/add.js';
            document.head.appendChild(script);
            Controller.api.bindevent();
        },
        edit: function () {
            var row = JSON.parse($('#row').val());
            var script = document.createElement('script');
            script.src = '/assets/js/backend/common/add.js';
            document.head.appendChild(script);
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            formatter: {//渲染的方法
                url: function (value, row, index) {
                    return '<div class="input-group input-group-sm" style="width:250px;"><input type="text" class="form-control input-sm" value="' + value + '"><span class="input-group-btn input-group-sm"><a href="' + value + '" target="_blank" class="btn btn-default btn-sm"><i class="fa fa-link"></i></a></span></div>';
                },
                ip: function (value, row, index) {
                    return '<a class="btn btn-xs btn-ip bg-success"><i class="fa fa-map-marker"></i> ' + value + '</a>';
                },
                status: function (value, row, index) {
                    var color = value == 1 ? 'success' : 'danger';
                    var icon = value == 1 ? 'fa-toggle-on' : 'fa-toggle-off';
                    var title = value == 1 ? '已通过' : '未通过';
                    return '<a href="javascript:;" class="btn-status" data-id="' + row.id + '" data-status="' + value + '" title="' + title + '">' +
                        '<i class="fa ' + icon + ' text-' + color + ' fa-2x"></i></a>';
                },
                changeStatus: function (value, row, index) {
                    //添加上btn-change可以自定义请求的URL进行数据处理
                    return '<a class="btn-change text-success" data-url="classes/student/classes/student/changeStatus" data-confirm="确认切换状态？" data-id="' + row.id + '"><i class="fa ' + (row.status === 0 ? 'fa-toggle-on fa-flip-horizontal text-gray' : 'fa-toggle-on') + ' fa-2x"></i></a>';
                },
                payButton: function(value, row, index) {
                    return '<button class="btn btn-xs btn-warning btn-pay" data-id="' + row.id + '">支付</button>';
                }
            },
            events: {//绑定事件的方法
                ip: {
                    //格式为：方法名+空格+DOM元素
                    'click .btn-ip': function (e, value, row, index) {
                        e.stopPropagation();
                        var container = $("#table").data("bootstrap.table").$container;
                        var options = $("#table").bootstrapTable('getOptions');
                        //这里我们手动将数据填充到表单然后提交
                        $("form.form-commonsearch [name='ip']", container).val(value);
                        $("form.form-commonsearch", container).trigger('submit');
                        Toastr.info("执行了自定义搜索操作");
                    }
                },
                pay: {
                    'click .btn-pay': function(e, value, row, index) {
                        e.stopPropagation();
                        // 调用支付接口
                        $.post('/api/v1/enrollment/native?sr='+Math.random(), {
                            user_id: row.student_id,
                            order_id: 1,
                            out_trade_no: 'class_' + row.id + '_' + Date.now(),
                            total_fee: row.price * 100, // 金额(分)
                            description: '报名班级:' + row.name
                        }, function(res) {
                            if (res.code === 200 && res.data.code_url) {
                                // 生成支付弹窗
                                debugger;
                                showPaymentDialog(res.data);
                            } else {
                                Layer.alert(res.msg || '下单失败');
                            }
                        }, 'json');
                    }
                }
            }
        }
    };
    return Controller;
});

// native 支付
function showPaymentDialog(paymentData) {
    var html = '<div style="text-align:center;padding:20px">' +
        '<div id="qrcode" style="margin:0 auto;width:200px;height:200px"></div>' +
        '<p style="margin-top:10px">订单号: ' + paymentData.order_sn + '</p>' +
        '<p>金额: ¥' + (paymentData.total_fee / 100) + '</p>' +
        '<p>请使用微信扫码支付</p>' +
        '</div>';

    var index = Layer.open({
        title: '微信支付',
        content: html,
        area: ['95%', '95%'],
        btn: ['支付完成', '取消支付'],
        yes: function() {
            checkPaymentStatus(paymentData.out_trade_no, index);
        },
        cancel: function() {
            // 取消支付逻辑
        }
    });

    // 生成二维码
    new QRCode(document.getElementById("qrcode"), {
        text: paymentData.code_url,
        width: 200,
        height: 200
    });
}

function checkPaymentStatus(outTradeNo, layerIndex) {
    var checkCount = 0;
    var maxChecks = 10;
    var interval = setInterval(function() {
        checkCount++;
        $.get('/classes/payment/check', {out_trade_no: outTradeNo}, function(res) {
            if (res.code === 1 && res.data.trade_state === 'SUCCESS') {
                clearInterval(interval);
                Layer.close(layerIndex);
                Layer.msg('支付成功', {icon: 1});
                // 刷新表格数据
                $('#table').bootstrapTable('refresh');
            } else if (checkCount >= maxChecks) {
                clearInterval(interval);
                Layer.alert('支付超时，请检查支付状态');
            }
        });
    }, 3000);
}